package org.qiyu.live.api.service.impl;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.common.message.Message;
import org.qiyu.live.api.service.IGiftService;
import org.qiyu.live.api.vo.req.GiftReqVO;
import org.qiyu.live.bank.interfaces.IQiyuCurrencyAccountRpc;
import org.qiyu.live.web.starter.context.QiyuRequestContext;
import org.qiyu.live.web.starter.error.ErrorAssert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import qiyu.live.gift.dto.GiftConfigDTO;
import qiyu.live.gift.dto.SendGiftMq;
import qiyu.live.gift.interfaces.IGiftConfigRpc;


import static org.qiyu.live.common.interfaces.topic.ImCoreServerProviderTopicNames.SEND_GIFT_TOPIC;
import static org.qiyu.live.web.starter.error.QiYuBaseErrorEnum.SEND_GIT_ERROR;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-11-03
 * Time: 19:27
 */
@Service
public class GiftServiceImpl implements IGiftService {

    private  final Logger logger = LoggerFactory.getLogger(GiftServiceImpl.class);

    @DubboReference
    private IGiftConfigRpc giftConfigRpc;
    @DubboReference
    private IQiyuCurrencyAccountRpc currencyAccountRpc;
    @Resource
    private MQProducer mqProducer;

    @Override
    public boolean send(GiftReqVO giftReqVO) {
        // 1. 查询礼物,对礼物做合法性判断
        GiftConfigDTO giftConfigDTO = giftConfigRpc.getByGiftId(giftReqVO.getGiftId());
        ErrorAssert.isNotNull(giftConfigDTO, SEND_GIT_ERROR);
        // 2. 检查用户的账户余额,如果充足进行扣减,否则返回错误.
        // 这里进行异步检查用户账户余额,并进行扣减,我们发送一个MQ消息
        SendGiftMq sendGiftMq = new SendGiftMq();
        sendGiftMq.setGiftId(giftReqVO.getGiftId());
        sendGiftMq.setPrice(giftConfigDTO.getPrice());
        sendGiftMq.setType(giftReqVO.getType());
        sendGiftMq.setUserId(QiyuRequestContext.getUserId());
        sendGiftMq.setRoomId(giftReqVO.getRoomId());
        Message message = new Message();
        message.setTopic(SEND_GIFT_TOPIC);
        message.setBody(JSON.toJSONBytes(sendGiftMq));
        try {
            mqProducer.send(message);
        } catch (Exception e) {
            logger.error("发送礼物给失败(异步mq)",e);
        }
        return true;
    }
}